package org.smart4j.chapter2.help;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;
import org.smart4j.chapter2.util.PropsUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * Created by xj on 2016/11/18.
 * 数据库操作助手类
 */
public final class DatabaseHelper {
    private static final Logger LOGGER = Logger.getLogger(DatabaseHelper.class);
    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final QueryRunner QUERY_RUNNER = new QueryRunner();
    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = new ThreadLocal<Connection>();

    static {
        Properties conf = PropsUtil.loadProps("config.properties");
        DRIVER = conf.getProperty("jdbc.dirver");
        URL = conf.getProperty("jdbc.url");
        USERNAME = conf.getProperty("jdbc.username");
        PASSWORD = conf.getProperty("jdbc.password");
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            LOGGER.error("载入MYSQL驱动包错误");
        }
    }

    /***
     * 打开数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = CONNECTION_THREAD_LOCAL.get();
        try {
            if (connection == null) {
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                CONNECTION_THREAD_LOCAL.set(connection);
            }

        } catch (SQLException e) {
            LOGGER.error("连接数据库失败", e);
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     *
     * @param connection
     */
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
                CONNECTION_THREAD_LOCAL.remove();
            } catch (SQLException e) {
                LOGGER.error("关闭数据库失败", e);
            }
        }
    }

    /***
     * 查询实体类
     *
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntitList(Class<T> entityClass, String sql, Object... params) {

        List<T> entityList;
        Connection conn = getConnection();
        try {
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
            return entityList;
        } catch (SQLException e) {
            LOGGER.error("查询实体类失败", e);
        } finally {
            closeConnection(conn);
        }

        return null;

    }


}
